package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import com.itheima.reggie.common.ConstantUtil;
import com.itheima.reggie.entity.Result;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Controller
public class UserController {

    @Autowired
    private UserService userService ;

    @Autowired
    private RedisTemplate redisTemplate ;

    @RequestMapping("/user/sendMsg")
    @ResponseBody
    public Result sendMsg (@RequestBody User user , HttpSession httpSession ){

        //获取电话号码
        String phone = user.getPhone();

        //获取验证码
        String s = RandomUtil.randomNumbers(4);

        System.out.println( " 验证码是：" + s  );

        //保存到绘画中
//        httpSession.setAttribute( ConstantUtil.LOGINCODE + phone , s );

        //将验证码保存到redis中，创建一个redisTemplate的opsForValue
        ValueOperations valueOperations = redisTemplate.opsForValue();

        valueOperations.set(ConstantUtil.LOGINCODE + phone , s , 5 , TimeUnit.MINUTES );

        return Result.success(null);

    }

    @RequestMapping("/user/login")
    @ResponseBody
    public Result login(@RequestBody Map<String ,String > map , HttpSession httpSession ){

        //获取电话
        String phone = map.get("phone");
        //获取验证码
        String requestCode = map.get("code");
        //通过电话从会话获取正确验证码
//        String sessionCode = (String) httpSession.getAttribute(phone);
        //这里也是创建一个opsForValue
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //获取其中的数据，根据电话
        String sessionCode = (String) valueOperations.get(ConstantUtil.LOGINCODE + phone);

        System.out.println("redis中的数据是" + sessionCode );

        //调用业务层
        Result<User> result = userService.Login(phone, requestCode, sessionCode);

        //要是返回值为1
        if ( result.getCode() == 1 ){

            httpSession.setAttribute( "user" ,  result.getData().getId() );

//            httpSession.removeAttribute(phone);

            //登录成功就移除redis里面的验证码
            redisTemplate.delete(ConstantUtil.LOGINCODE + phone );

        }

        System.out.println(  "user会话元素是" + httpSession.getAttribute("user"));

        return result ;

    }

}
